package com.cskaoyan.service;

import com.aliyun.oss.OSSClient;
import com.aliyun.oss.model.PutObjectResult;
import com.cskaoyan.mapper.*;

import com.cskaoyan.module.bean.BaseRespVo;
import com.cskaoyan.module.pojo.*;
import com.cskaoyan.module.systemVO.*;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.javassist.bytecode.stackmap.BasicBlock;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.Date;
import java.util.LinkedList;
import java.util.List;
import java.util.UUID;

/**
 * Created with IntelliJ IDEA.
 *
 * @Description:
 * @Author: 周佳豪
 * @Date: 2022/04/06/20:48
 */
@Service
public class SystemServiceImpl implements SystemService {

    @Autowired
    MarketRoleMapper marketRoleMapper;
    @Autowired
    MarketAdminMapper marketAdminMapper;
    @Autowired
    MarketStorageMapper StorageMapper;
    @Autowired
    MarketLogMapper LogMapper;
    @Autowired
    MarketPermissionMapper marketPermissionMapper;

    BaseRespVo<Object> baseRespVo = new BaseRespVo<>();

    @Value("${my.path}")
    String path;


    @Override
    public BaseRespVo createAdmin(MarketAdmin marketAdmin) {
        if (marketAdmin.getPassword().length() < 6) {
            baseRespVo.setErrno(602);
            baseRespVo.setErrmsg("管理员密码长度不能小于6");
            return baseRespVo;
        }
        MarketAdminExample marketAdminExample = new MarketAdminExample();
        MarketAdminExample.Criteria criteria = marketAdminExample.createCriteria();
        criteria.andUsernameEqualTo(marketAdmin.getUsername());
        List<MarketAdmin> marketAdmins = marketAdminMapper.selectByExample(marketAdminExample);
        if (marketAdmins.size() != 0) {
            baseRespVo.setData(null);
            baseRespVo.setErrmsg("用户名已存在");
            baseRespVo.setErrno(602);
            return baseRespVo;
        }
        marketAdmin.setAddTime(new Date());
        marketAdmin.setUpdateTime(new Date());
        marketAdmin.setDeleted(false);
        int insert = marketAdminMapper.insert(marketAdmin);
        MarketAdmin marketAdmin1 = marketAdminMapper.selectByPrimaryKey(marketAdmin.getId());
        baseRespVo.setData(marketAdmin1);
        baseRespVo.setErrmsg("成功");
        baseRespVo.setErrno(0);
        return baseRespVo;
    }

    @Override
    public BaseRespVo createRole(MarketRole marketRole) {
        MarketRoleExample example = new MarketRoleExample();
        MarketRoleExample.Criteria criteria = example.createCriteria();
        criteria.andNameEqualTo(marketRole.getName());
        List<MarketRole> marketRoleList = marketRoleMapper.selectByExample(example);
        if (marketRoleList.size() != 0) {
            baseRespVo.setData(null);
            baseRespVo.setErrmsg("用户名已存在");
            baseRespVo.setErrno(602);
            return baseRespVo;
        }

        marketRole.setEnabled(true);
        marketRole.setDeleted(false);
        marketRole.setAddTime(new Date());
        marketRole.setUpdateTime(new Date());
        //先插入数据
        int insert = marketRoleMapper.insert(marketRole);
        //获取自增的主键
        Integer id = marketRole.getId();
        System.out.println(id);
        //返回数据没有enabled和deleted 所以用的SQL语句用的<sql id="Base_Column_List_create">
        //用自增的主键查询
        MarketRole marketRole1 = marketRoleMapper.selectByPrimaryKey(id);
        baseRespVo.setData(marketRole1);
        baseRespVo.setErrmsg("成功");
        baseRespVo.setErrno(0);
        return baseRespVo;
    }

    @Override
    public BaseRespVo updateRole(MarketRole marketRole) {

        //example是条件
        MarketRoleExample example = new MarketRoleExample();
        MarketRoleExample.Criteria criteria = example.createCriteria();
        //条件是id等于某个数
        criteria.andIdEqualTo(marketRole.getId());
        int i = marketRoleMapper.updateByExampleSelective(marketRole, example);
        if (i == 1) {
            baseRespVo.setErrno(0);
            baseRespVo.setErrmsg("");
        }
        return baseRespVo;
    }

    @Override
    public BaseRespVo listRole(Integer page, Integer limit, String name, String sort, String order) {
        //分页插件
        PageHelper.startPage(page, limit);
        //根据sort和order查询
        MarketRoleExample example = new MarketRoleExample();
        MarketRoleExample.Criteria criteria = example.createCriteria();
        if (name != null) {
            criteria.andNameLike("%" + name + "%");
        }
        example.setOrderByClause(sort + " " + order);
        //查询所有数据
        List<MarketRole> marketRoleList = marketRoleMapper.selectByExample(example);
        //new一个返回的gson对象
        PageInfo<MarketRole> pageInfo = new PageInfo<>(marketRoleList);

        RoleUpdateVO roleUpdateVO = new RoleUpdateVO((int) pageInfo.getTotal(),pageInfo.getPages(), pageInfo.getPageSize(), pageInfo.getPageNum(), marketRoleList);
        baseRespVo.setData(roleUpdateVO);
        baseRespVo.setErrno(0);
        baseRespVo.setErrmsg("成功");
        return baseRespVo;
    }

    @Override
    public BaseRespVo deleteRole(MarketRole marketRole) {
        int i = marketRoleMapper.deleteByPrimaryKey(marketRole.getId());
        if (i == 1) {
            baseRespVo.setErrno(0);
            baseRespVo.setErrmsg("成功");
            return baseRespVo;
        } else {
            baseRespVo.setErrno(642);
            baseRespVo.setErrmsg("当前用户存在管理员，不能删除");
            return baseRespVo;
        }
    }

    @Override
    public BaseRespVo createStorage(MultipartFile uploadFile, HttpServletRequest request) {
        String accessKeyId = "LTAI5tMegeHNWNhwLcJWUKQ8";
        String accessKeySecret = "i1NWpImPOePGok7EKYfY5Vn72SOUiK";
        String bucket = "project2file";
        String endPoint = "oss-cn-beijing.aliyuncs.com";
        String name = uploadFile.getOriginalFilename();
        String[] split = name.split("\\.");
        String oldName = "."+split[1];
        InputStream inputStream = null;
        try {
            inputStream = uploadFile.getInputStream();
        } catch (IOException e) {
            e.printStackTrace();
        }
        String newName = UUID.randomUUID().toString()+oldName;

        OSSClient ossClient = new OSSClient(endPoint, accessKeyId, accessKeySecret);

        PutObjectResult putObjectResult = ossClient.putObject(bucket, newName,inputStream);

        String saveName = "https://"+bucket+"."+endPoint+"/"+newName;

        MarketStorage marketStorage = new MarketStorage();
        marketStorage.setKey(newName);
        marketStorage.setName(oldName);
        String type = oldName.substring(oldName.lastIndexOf(".") + 1, oldName.length());
        marketStorage.setType("image/" + type);
        Integer size = (int) uploadFile.getSize();
        marketStorage.setSize(size);
        marketStorage.setUrl(saveName);
        marketStorage.setAddTime(new Date());
        marketStorage.setUpdateTime(new Date());
        marketStorage.setDeleted(false);
        int insert = StorageMapper.insert(marketStorage);
        if (insert == 1) {
            baseRespVo.setErrno(0);
            baseRespVo.setData(marketStorage);
            baseRespVo.setErrmsg("成功");
        }
        return baseRespVo;
    }

    @Override
    public BaseRespVo roleOptions() {
        List<RoleIdAndNameVO> list = marketRoleMapper.selectRoleOptions();
        RoleOptionsVO roleOptionsVO = new RoleOptionsVO(list.size(), 1, list.size(), 1, list);
        baseRespVo.setErrno(0);
        baseRespVo.setData(roleOptionsVO);
        baseRespVo.setErrmsg("成功");
        return baseRespVo;
    }

    @Override
    public BaseRespVo listAdmin(Integer page, Integer limit, String username, String sort, String order) {
        PageHelper.startPage(page, limit);
        MarketAdminExample example = new MarketAdminExample();
        example.setOrderByClause(sort + " " + order);
        if (username != null) {
            MarketAdminExample.Criteria criteria = example.createCriteria().andUsernameLike("%" + username + "%");
        }
        List<AdminLIstIdAndName> list = marketAdminMapper.selectIdAndNameByExample(example);

        //new一个返回的gson对象
        PageInfo<AdminLIstIdAndName> pageInfo = new PageInfo<>(list);

        AdminListVO adminListVO = new AdminListVO((int) pageInfo.getTotal(),pageInfo.getPages(), pageInfo.getPageSize(), pageInfo.getPageNum(),  list);
        baseRespVo.setData(adminListVO);
        baseRespVo.setErrno(0);
        baseRespVo.setErrmsg("成功");
        return baseRespVo;
    }

    @Override
    public BaseRespVo updateAdmin(MarketAdmin marketAdmin) {
        if (marketAdmin.getPassword().length() < 6) {
            baseRespVo.setErrno(602);
            baseRespVo.setErrmsg("管理员密码长度不能小于6");
            return baseRespVo;
        }
        int i = marketAdminMapper.updateByPrimaryKeySelective(marketAdmin);
        MarketAdmin returnAdmin = marketAdminMapper.selectByPrimaryKey(marketAdmin.getId());
        baseRespVo.setErrno(0);
        baseRespVo.setData(returnAdmin);
        baseRespVo.setErrmsg("成功");
        return baseRespVo;
    }

    @Override
    public BaseRespVo deleteAdmin(MarketAdmin marketAdmin) {
        int i = marketAdminMapper.deleteByPrimaryKey(marketAdmin.getId());
        if (i == 1) {
            baseRespVo.setErrno(0);
            baseRespVo.setErrmsg("成功");
        }
        return baseRespVo;
    }

    @Override
    public BaseRespVo listLog(Integer page, Integer limit, String name, String sort, String order) {
        PageHelper.startPage(page, limit);
        MarketLogExample marketLogExample = new MarketLogExample();
        if (name != null) {
            marketLogExample.createCriteria().andAdminLike("%" + name + "%");
        }
        marketLogExample.setOrderByClause(sort + " " + order);
        List<MarketLog> marketLogs = LogMapper.selectByExample(marketLogExample);
        //new一个返回的gson对象
        PageInfo<MarketLog> pageInfo = new PageInfo<>(marketLogs);

        LogListVO logListVO = new LogListVO((int) pageInfo.getTotal(),pageInfo.getPages(), pageInfo.getPageSize(), pageInfo.getPageNum(),  marketLogs);
        baseRespVo.setData(logListVO);
        baseRespVo.setErrno(0);
        baseRespVo.setErrmsg("成功");
        return baseRespVo;
    }

    @Override
    public BaseRespVo listStorage(Integer page, Integer limit, String key, String name, String sort, String order) {
        PageHelper.startPage(page, limit);
        MarketStorageExample example = new MarketStorageExample();
        MarketStorageExample.Criteria criteria = example.createCriteria();
        if (key != null) {
            criteria.andKeyLike("%" + key + "%");
        }
        if (name != null) {
            criteria.andNameLike("%" + name + "%");
        }
        example.setOrderByClause(sort + " " + order);
        List<MarketStorage> marketStorages = StorageMapper.selectByExample(example);
        //new一个返回的gson对象
        PageInfo<MarketStorage> pageInfo = new PageInfo<>(marketStorages);
        //拿到的数据总量

        StorageList storageList = new StorageList((int) pageInfo.getTotal(),pageInfo.getPages(), pageInfo.getPageSize(), pageInfo.getPageNum(),  marketStorages);
        baseRespVo.setData(storageList);
        baseRespVo.setErrno(0);
        baseRespVo.setErrmsg("成功");
        return baseRespVo;
    }

    @Override
    public BaseRespVo updateStorage(MarketStorage marketStorage) {
        int i = StorageMapper.updateByPrimaryKey(marketStorage);
        if (i == 1) {
            baseRespVo.setErrno(0);
            baseRespVo.setErrmsg("成功");
        }
        return baseRespVo;
    }

    @Override
    public BaseRespVo deleteStorage(MarketStorage marketStorage) {
        int i = StorageMapper.deleteByPrimaryKey(marketStorage.getId());
        if (i == 1) {
            baseRespVo.setErrno(0);
            baseRespVo.setErrmsg("成功");
        }
        return baseRespVo;
    }

    @Override
    public BaseRespVo rolePermissions(Integer roleId) {
        //直接查的权限
        List<String> assignedPermissions = new LinkedList<>();
        assignedPermissions = marketRoleMapper.selectPermissions(roleId);
        //所有权限
        RolePermissionsVO rolePermissionsVO = new RolePermissionsVO();
        rolePermissionsVO.setAssignedPermissions(assignedPermissions);
        // 查询pid为0的id
        List<Integer> list = marketRoleMapper.selectPermissionFids(0);
        //这是最大的一个父list
        List<SystemPermissionsVO> systemPermissionsVOS = new LinkedList<>();

        for (Integer id : list) {
            //要封装到list里面的对象
            SystemPermissionsVO systemPermissionsVO = new SystemPermissionsVO();
            String name = marketRoleMapper.selectPermissionName(id);
            String label = marketRoleMapper.selectPermissionLabel(id);
            systemPermissionsVO.setId(name);
            systemPermissionsVO.setLabel(label);

            // 查询pid不为0的id
            List<Integer> sid = marketRoleMapper.selectPermissionFids(id);
            //这是最第二大的一个子list
            List<SystemChildren1VO> systemChildren1VOS = new LinkedList<>();

            for (Integer pid : sid) {
                //要封装到list里面的对象
                SystemChildren1VO systemChildren1VO = new SystemChildren1VO();
                String s = marketRoleMapper.selectPermissionName(pid);
                String plabel = marketRoleMapper.selectPermissionLabel(pid);
                systemChildren1VO.setId(s);
                systemChildren1VO.setLabel(plabel);

                LinkedList<SystemChildren2VO> systemChildren2VOS = new LinkedList<>();
                systemChildren2VOS = marketRoleMapper.selectPermissionC(pid);
                systemChildren1VO.setChildren(systemChildren2VOS);
                systemChildren1VOS.add(systemChildren1VO);
            }

            systemPermissionsVO.setChildren(systemChildren1VOS);
            systemPermissionsVOS.add(systemPermissionsVO);
        }
        rolePermissionsVO.setSystemPermissions(systemPermissionsVOS);
        baseRespVo.setData(rolePermissionsVO);
        baseRespVo.setErrno(0);
        baseRespVo.setErrmsg("成功");
        return baseRespVo;
    }

    @Override
    public BaseRespVo updatePermissions(PermissionsBO permissionsBO) {
        List<String> permissions = permissionsBO.getPermissions();
        Integer roleId = permissionsBO.getRoleId();
        for (String permission : permissions) {
            MarketPermission marketPermission = new MarketPermission();
            marketPermission.setRoleId(roleId);
            marketPermission.setPermission(permission);
            marketPermission.setAddTime(new Date());
            marketPermission.setUpdateTime(new Date());
            marketPermission.setDeleted(false);
            MarketPermissionExample example = new MarketPermissionExample();
            MarketPermissionExample.Criteria criteria = example.createCriteria();
            criteria.andPermissionEqualTo(permission);
            criteria.andRoleIdEqualTo(roleId);
            List<MarketPermission> marketPermissions = new LinkedList<>();
            marketPermissions = marketPermissionMapper.selectByExample(example);
            if (marketPermissions.size()==0) {
                int insert = marketPermissionMapper.insert(marketPermission);
            }else continue;
        }
        baseRespVo.setErrno(0);
        baseRespVo.setErrmsg("成功");
        return baseRespVo;
    }
}
